package com.lifl.ecogarde;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.client.CookieStore;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.lifl.ecogarde.ajout.ComportementAjoutActivity;
import com.lifl.ecogarde.ajout.infosComp.InfosCompAmphibiensAjoutActivity;
import com.lifl.ecogarde.ajout.infosComp.InfosCompArachnidesAjoutActivity;
import com.lifl.ecogarde.ajout.infosComp.InfosCompChauveAjoutActivity;
import com.lifl.ecogarde.ajout.infosComp.InfosCompCoccinellesAjoutActivity;
import com.lifl.ecogarde.ajout.infosComp.InfosCompFloresAjoutActivity;
import com.lifl.ecogarde.ajout.infosComp.InfosCompFongeAjoutActivity;
import com.lifl.ecogarde.ajout.infosComp.InfosCompInsectesAjoutActivity;
import com.lifl.ecogarde.ajout.infosComp.InfosCompLibellulesAjoutActivity;
import com.lifl.ecogarde.ajout.infosComp.InfosCompMammifereAjoutActivity;
import com.lifl.ecogarde.ajout.infosComp.InfosCompMollusquesAjoutActivity;
import com.lifl.ecogarde.ajout.infosComp.InfosCompMoussesAjoutActivity;
import com.lifl.ecogarde.ajout.infosComp.InfosCompOiseauxAjoutActivity;
import com.lifl.ecogarde.ajout.infosComp.InfosCompPapillonsAjoutActivity;
import com.lifl.ecogarde.ajout.infosComp.InfosCompPoissonsAjoutActivity;

public class ValiderAjoutActivity extends Activity {

	private final String TAG = "ValiderAjoutActivity";
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
	private Uri fileUri;
	private Bitmap scaledBitmap = null;
	protected NotePool pool;

	Note n = new Note();
	String id = "";
	List<SerializableCookie> SerializableCookieStore;
	CookieStore FirstCookieStore;
	ArrayList<String> arrayList = new ArrayList<String>();

	public ValiderAjoutActivity() {
		pool = new NotePool(this);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.valider_ajout);
		setTitle("EcoGarde > Valider l'observation");
		Log.d(TAG, "valider obs");
		n = (Note) getIntent().getExtras().get("obs");
		id = getIntent().getExtras().getString("id");

		SerializableCookieStore = (List<SerializableCookie>) getIntent()
				.getExtras().get("SerializableCookieStore");

		/*if (n.getContentByKey(Constantes.PHO) != null) {
			scaledBitmap = ((PhotoContent) n.getContentByKey(Constantes.PHO))
					.getBitmap();
			ImageView imageView = (ImageView) findViewById(R.id.IVphoto);
			imageView.setImageBitmap(scaledBitmap);
		}*/

		FirstCookieStore = new BasicCookieStore();

		for (int i = 0; i < SerializableCookieStore.size(); i++) {
			FirstCookieStore.addCookie(SerializableCookieStore.get(i)
					.getCookie());
			Log.d(TAG, "VVVVVVVVVVVVVVVVVVV Local cookie: "
					+ SerializableCookieStore.get(i).getCookie());
		}

		Log.d(TAG, "id_choisi: " + id);
		setListView();
		Log.d(TAG, "Fin de l'activité");
	}

	private Intent createIntent(Class cls) {
		Intent result = new Intent(getBaseContext(), cls);
		result.putExtra("SerializableCookieStore",
				(Serializable) SerializableCookieStore);
		return result;
	}

	public void onClickInfosCompl(View view) {
		Log.d(TAG, "id: " + id);
		switch (Integer.parseInt(id)) {
		case 1:// Mammifres
			Intent intent1 = createIntent(InfosCompMammifereAjoutActivity.class);
			intent1.putExtra("id", id);
			intent1.putExtra("obs", n);
			startActivity(intent1);
			break;
		case 2:// Chauve-souris
			Intent intent2 = createIntent(InfosCompChauveAjoutActivity.class);
			intent2.putExtra("id", id);
			intent2.putExtra("obs", n);
			startActivity(intent2);
			break;
		case 3:// Oiseaux
			Intent intent3 = createIntent(InfosCompOiseauxAjoutActivity.class);
			intent3.putExtra("id", id);
			intent3.putExtra("obs", n);
			startActivity(intent3);
			break;
		case 4:// Poissons
			Intent intent4 = createIntent(InfosCompPoissonsAjoutActivity.class);
			intent4.putExtra("id", id);
			intent4.putExtra("obs", n);
			startActivity(intent4);
			break;
		case 5:// Amphibiens
			Intent intent5 = createIntent(InfosCompAmphibiensAjoutActivity.class);
			intent5.putExtra("id", id);
			intent5.putExtra("obs", n);
			startActivity(intent5);
			break;
		case 6:// Papillons
			Intent intent6 = createIntent(InfosCompPapillonsAjoutActivity.class);
			intent6.putExtra("id", id);
			intent6.putExtra("obs", n);
			startActivity(intent6);
			break;
		case 7:// Coccinelles
			Intent intent7 = createIntent(InfosCompCoccinellesAjoutActivity.class);
			intent7.putExtra("id", id);
			intent7.putExtra("obs", n);
			startActivity(intent7);
			break;
		case 8:// Libellules
			Intent intent8 = createIntent(InfosCompLibellulesAjoutActivity.class);
			intent8.putExtra("id", id);
			intent8.putExtra("obs", n);
			startActivity(intent8);
			break;
		case 9:// Arachnides
			Intent intent9 = createIntent(InfosCompArachnidesAjoutActivity.class);
			intent9.putExtra("id", id);
			intent9.putExtra("obs", n);
			startActivity(intent9);
			break;
		case 10:// insectes
			Intent intent10 = createIntent(InfosCompInsectesAjoutActivity.class);
			intent10.putExtra("id", id);
			intent10.putExtra("obs", n);
			startActivity(intent10);
			break;
		case 11:// Fonges
			Intent intent11 = createIntent(InfosCompFongeAjoutActivity.class);
			intent11.putExtra("id", id);
			intent11.putExtra("obs", n);
			startActivity(intent11);
			break;
		case 12:// Flores
			Intent intent12 = createIntent(InfosCompFloresAjoutActivity.class);
			intent12.putExtra("id", id);
			intent12.putExtra("obs", n);
			startActivity(intent12);
			break;
		case 13:// Mollusques
			Intent intent13 = createIntent(InfosCompMollusquesAjoutActivity.class);
			intent13.putExtra("id", id);
			intent13.putExtra("obs", n);
			startActivity(intent13);
			break;
		case 14:// Mousses/lichens
			Intent intent14 = createIntent(InfosCompMoussesAjoutActivity.class);
			intent14.putExtra("id", id);
			intent14.putExtra("obs", n);
			startActivity(intent14);
			break;
		case 15:// Reptiles
			Toast toast = Toast
					.makeText(
							getApplicationContext(),
							"Aucune information disponible pour le groupe d'espces reptiles",
							Toast.LENGTH_LONG);
			toast.show();
			break;
		}
	}

	public void onValidAjout(View view) {
		n.addContent("id", new EntierContent(Integer.parseInt(id)), "");

		HttpContext localContext = new BasicHttpContext();
		localContext.setAttribute(ClientContext.COOKIE_STORE, FirstCookieStore);

		pool.god.browser.setContext(localContext);
		pool.god.setContext(localContext);
		pool.addNote(n, -1, -1, new Handler() {

			@Override
			public void onResponse(Object... objet) {
				MonLog.print("Observation ajouté", getClass());
				Toast toast = Toast.makeText(getApplicationContext(),
						"Observation ajoutÈe", Toast.LENGTH_LONG);
				pool.god.closed();
				toast.show();
			}

			@Override
			public void onError() {
				MonLog.print("Observation non ajouté", getClass());
				Toast toast = Toast.makeText(getApplicationContext(),
						"Observation non ajoutÈe", Toast.LENGTH_LONG);
				pool.god.closed();
				toast.show();
			}

			@Override
			public void onRelease() {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgress() {
				// TODO Auto-generated method stub

			}

		});

		Intent intent = new Intent(getBaseContext(), EcoGardeActivity.class);
		intent.putExtra("SerializableCookieStore", getIntent().getExtras()
				.getSerializable("SerializableCookieStore"));
		startActivity(intent);
		this.finish();
	}

	private void setListView() {

		Map<String, String> Result = observationToString();

		Log.d(TAG, "début map");

		Iterator<String> it = Result.keySet().iterator();
		while (it.hasNext()) // tant que j'ai un element non parcouru
		{
			String cle = it.next();
			String Value = cle + ": " + Result.get(cle);
			arrayList.add(Value);
			Log.i(TAG, "List item: " + Value);
		}

		ListView lv = (ListView) findViewById(R.id.listChoixEffectues);

		ArrayAdapter<String> adapter_choix = new ArrayAdapter<String>(
				getApplicationContext(), R.layout.item_list_choix,
				R.id.item_choix, arrayList);
		lv.setAdapter(adapter_choix);

		Log.d(TAG, "fin de la map");
	}

	public Map<String, String> observationToString() {
		Map<String, String> res = new HashMap<String, String>();
		Log.d(TAG, "début de l'observation");

		Iterator<String> it = n.contents.keySet().iterator();
		while (it.hasNext()) // tant que j'ai un element non parcouru
		{
			String champs = it.next();
			Content content = n.contents.get(champs);
			Log.d(TAG, champs);
			if (champs.equals(Constantes.XY)) {
				res.put(Constantes.X,
						((CoordonneesContent) content).getLongitude() + "");
				res.put(Constantes.Y,
						((CoordonneesContent) content).getLatitude() + "");
			} else if (champs.equals(Constantes.DEB))
				res.put(Constantes.DEB, n.dateToString(((DateContent) n
						.getContentByKey(Constantes.DEB)).getDate()));
			else if (champs.equals(Constantes.FIN))
				res.put(Constantes.FIN, n.dateToString(((DateContent) n
						.getContentByKey(Constantes.FIN)).getDate()));
			else if (champs.equals(Constantes.NBR_IND))
				res.put(Constantes.NBR_IND,
						((EntierContent) content).getEntier() + "");
			else
				res.put(champs, ((TextContent) content).getText());
		}

		Log.d(TAG, "Fin de l'observation");
		return res;
	}

	public void onCaptureImage(View v) {
		findViewById(R.id.infoComp).setEnabled(false);
		// define the file-name to save photo taken by Camera activity
		String fileName = "new-photo-name.jpg";
		// create parameters for Intent with filename
		ContentValues values = new ContentValues();
		values.put(MediaStore.Images.Media.TITLE, fileName);
		values.put(MediaStore.Images.Media.DESCRIPTION,
				"Image capture by camera");
		// fileUri is the current activity attribute, define and save it for
		// later usage (also in onSaveInstanceState)
		fileUri = getContentResolver().insert(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
		// create new Intent
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
		intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
		startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {

			if (resultCode == Activity.RESULT_OK) {
				Uri selectedImage = fileUri;
				getContentResolver().notifyChange(selectedImage, null);
				ImageView imageView = (ImageView) findViewById(R.id.IVphoto);
				ContentResolver cr = getContentResolver();
				Bitmap bitmap;
				try {
					bitmap = android.provider.MediaStore.Images.Media
							.getBitmap(cr, selectedImage);

					scaledBitmap = Bitmap.createScaledBitmap(bitmap, 960, 720,
							true);
					// imageView.setImageBitmap(scaledBitmap);
					imageView
							.setImageBitmap(getResizedBitmap(bitmap, 960, 720));

					//n.addContent(Constantes.PHO, new PhotoContent(scaledBitmap), Constantes.PHO);

					// Toast.makeText(this, selectedImage.toString(),
					// Toast.LENGTH_LONG).show();
				} catch (Exception e) {
					Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
							.show();
					Log.e("Camera", e.toString());
				}

			} else if (resultCode == RESULT_CANCELED) {
				Toast.makeText(this, "Picture was not taken",
						Toast.LENGTH_SHORT);
			} else {
				Toast.makeText(this, "Picture was not taken",
						Toast.LENGTH_SHORT);
			}
		}
	}

	public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
		int width = bm.getWidth();
		int height = bm.getHeight();
		Log.d(TAG, "width = " + width + "  height = " + height);
		Toast.makeText(this, "width = " + width + "  height = " + height,
				Toast.LENGTH_SHORT);
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
				matrix, false);
		return resizedBitmap;
	}

	@Override
	protected void onDestroy() {
		pool.god.closed();
		super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		n.removeContent(Constantes.COMP);
		//n.removeContent(Constantes.PHO);
		Intent intent = new Intent(getBaseContext(),
				ComportementAjoutActivity.class);
		intent.putExtra("SerializableCookieStore", getIntent().getExtras()
				.getSerializable("SerializableCookieStore"));
		intent.putExtra("obs", n);
		intent.putExtra("id", id);
		startActivity(intent);
		this.finish();
		return true;
	}

}
